package com.arlain.mq.rocket.clustering;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;

import java.util.Date;

/**
 * Broadcasting is sending a message to all subscribers of a topic. If you want all subscribers receive messages about a topic, broadcasting is a good choice.
 */
public class BroadcastProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("clusteringProducer", new RPCHook() {
            @Override
            public void doBeforeRequest(String remoteAddr, RemotingCommand request) {
                System.out.println("doBeforeRequest");
            }

            @Override
            public void doAfterResponse(String remoteAddr, RemotingCommand request, RemotingCommand response) {
                System.out.println("doAfterResponse");
            }
        });
        producer.setNamesrvAddr("10.201.7.160:9876");
        producer.setInstanceName("clusteringProducer");
        producer.start();

        for (int i = 0; i < 1; i++) {
            Message msg = new Message("TopicBroadcast",
                    "TagA",
                    "OrderID188",
                    ("Hello world-" + i + " " + new Date()).getBytes(RemotingHelper.DEFAULT_CHARSET));
//            SendResult sendResult = producer.send(msg);
//            System.out.printf("%s%n", sendResult);
            //        producer.shutdown(); // todo SendCallback 会异步处理消息，不会阻塞等在返回结果，故 producer.shutdown() 要延后执行，集成spring 后也不需要 shutdown()
           producer.send(msg, new SendCallback() {

                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.printf("onSuccess %s%n", sendResult);
                }

                @Override
                public void onException(Throwable e) {
                    e.printStackTrace();
                    System.out.printf("onException %s%n", e);
                }
            });
        }

    }
}